package com.david.viewtest.view


import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.updateLayoutParams
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.david.viewtest.R

/**
 * 层叠头像View
 * 使用示例：
<com.zeekrlife.components.AvatarsView
android:id="@+id/avatars_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
/>

设置头像：
findViewById<AvatarsView>(R.id.avatars_view).setImgUrls(arrayListOf(
"https://zeekrlife-oss.zeekrlife.com/IMAGE/1/manage/1001/zeekrlife-mp-osp/20240124/5ea4d74c8d8c43619bf4b2a1d9eaaa53.jpg",
"https://zeekrlife-oss-test.lkhaowu.com/default-avatar/7.png",
"https://zeekrlife-oss.zeekrlife.com/IMAGE/1/manage/2195/zeekrlife-mp-osp/20221114/191130e4cd9f46c2b645919872d2e498.jpeg",
"https://zeekrlife-oss-test.lkhaowu.com/IMAGE/1/manage/731/zeekrlife-mp-osp/20231219/20c2a275e4ca49cfb790f57da1939226.jpg",
))
 */
class AvatarsView(context: Context, attr: AttributeSet) : View(context, attr) {
    var text = "文案文案"
    var restNumber = "+10086"

    /**
     * 图片加载中的占位图
     */
    private var holderBitmap: Bitmap

    private val paint = Paint()

    val bitmaps = ArrayList<Bitmap>()

    /**
     * avatar大小包含边框的
     */
    val avatarSize = 40

    /**
     * 边框宽度
     */
    private val borderWidth = 2f

    /**
     * 头像层叠宽度，设置负值时为头像间的间隔
     */
    val avatarLeftOffset = 12



    private val minusOffsetWidth = avatarSize - avatarLeftOffset

    private val halfAvatarSize = avatarSize / 2f


    /**
     * 文字与左边头像间隔
     */
    val textAvatarDistance = 20f

    init {
        paint.strokeWidth = borderWidth
        paint.textSize = 14f
    }

    private var imgRect = Rect(0, 0, 0, 0)
    private var dstRect = Rect(0, 0, 0, 0)

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        for (index in (bitmaps.size - 1) downTo (0)) {
            val item = bitmaps[index]
            imgRect.left = 0
            imgRect.top = 0
            imgRect.right = item.width
            imgRect.bottom = item.height

            //- + 1避免头像与边框之间出现间隙
            dstRect.left = (index * (minusOffsetWidth) + borderWidth).toInt() - 1
            dstRect.top = borderWidth.toInt() - 1
            dstRect.right = ((index * (minusOffsetWidth) + avatarSize) - borderWidth).toInt() + 1
            dstRect.bottom = (avatarSize - borderWidth).toInt() + 1
            canvas.drawBitmap(
                item,
                imgRect,
                dstRect,
                paint
            )

            paint.color = Color.WHITE

            paint.style = Paint.Style.STROKE
            canvas.drawCircle(index * (minusOffsetWidth) + halfAvatarSize, halfAvatarSize, (avatarSize - borderWidth) / 2f, paint)
        }

        paint.style = Paint.Style.FILL
        paint.color = Color.parseColor("#24292b")

        val titleStartY = (height / 2f) - (paint.descent() + paint.ascent()) / 2f

        canvas.drawText(restNumber, (bitmaps.size - 1) * (minusOffsetWidth) + avatarSize + textAvatarDistance, titleStartY, paint)

        paint.color = Color.parseColor("#8E9496")
        canvas.drawText(text, (bitmaps.size - 1) * (minusOffsetWidth) + avatarSize + textAvatarDistance + paint.measureText(restNumber) + 3, titleStartY, paint)
    }

    fun setImgUrls(imgUrls: List<String>?) {
        bitmaps.clear()
        if (imgUrls.isNullOrEmpty()) {
            postInvalidate()
            return
        }

        for (i in imgUrls.indices) {
            bitmaps.add(holderBitmap)
        }
        postInvalidate()
        for ((index, imgUrl) in imgUrls.withIndex()) {
            Glide.with(context)
                .asBitmap()
                .load(turnRound(imgUrl, 25, 25, 25))
                .circleCrop()
                .into(object : CustomTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?,
                    ) {
                        if (index < bitmaps.size) {
                            bitmaps.removeAt(index)
                            bitmaps.add(index, resource)
                            postInvalidate()
                        }
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                    }
                })
        }

        post {
            updateLayoutParams<ViewGroup.LayoutParams> {
                width = ((avatarSize - 1) * imgUrls.size + avatarSize + textAvatarDistance + paint.measureText(text)).toInt()
                height = avatarSize.toInt()
            }
        }
    }

    private fun getBitmap(context: Context, resId: Int): Bitmap {
        return resources.getDrawable(resId, null).toBitmap()
    }

    init {
        holderBitmap = getBitmap(context, R.mipmap.ic_launcher_round)
        setImgUrls(null)
    }

    private fun getDimen(resId: Int): Float {
        return resources.getDimension(resId)
    }

    fun turnRound(
        originImageUrl: String?,
        width: Int,
        height: Int,
        radius: Int, //圆角多大
    ): String {
        if (TextUtils.isEmpty(originImageUrl)) {
            return ""
        }
        if (originImageUrl!!.endsWith("/format,webp") || originImageUrl.contains("?x-oss-process=image") || originImageUrl.contains(".gif")) {
            return originImageUrl
        }
        return "$originImageUrl?x-oss-process=image/resize,m_fill,h_$height,w_$width/rounded-corners,r_$radius/format,png"
    }
}